//
//  CLStatusViewModel.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/13.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit
//这个viewModel对应的是tableView的cell外观显示
class CLStatusViewModel: NSObject {

    //转发量显示内容
    var reweetStr:String?
    //评论数
    var commentStr:String?
    //赞
    var unlikeStr: String?
    //处理转发微博@内容拼接
    var reweetContent:String?
    //认证类型等级图片
    var verifiedTypeImage:UIImage?
    //会员等级图片
    var mbrankImage:UIImage?
    //来源
    var sourceContent:String?
    
    
    //这里处理显示内容的逻辑
    var status:CLStatus?
    //原创微博富文本
    var originalAttributedStr:NSAttributedString?
    //转发微博富文本
    var retweetAttributedStr:NSAttributedString?
    
    init(status :CLStatus) {
        super.init()
        self.status = status
        //转发
        reweetStr = handleCount(status.reposts_count, title: "转发")
        commentStr = handleCount(status.comments_count, title: "评论")
        unlikeStr = handleCount(status.attitudes_count, title: "赞")
        //处理转发微博内容显示
        handleReweetContent(status)
        //处理认证等级显示
        handleVerifiedTypeImage(status.user?.verified_type ?? 0)
        //处理字符串来源
        handleSourceContent(status.source ?? "")
        //处理会员等级
        handleMBrankImage(status.user?.mbrank ?? 0)
        //处理首页微博原创内容显示富文本
        originalAttributedStr = handleEmoiconContentWithAttachment(status.text!)
    }
    //发微博时间  把时间设为计算属性 因为每次滚动cell 的时候都需要跟我们当前的时间进行比较
    var time:String? {
        guard let creatAtStr = self.status?.created_at else {
            return nil
        }
        return NSDate.myDate(creatAtStr).myDateToString
//        print(creatAtStr)
        //转换成时间对象
//        let dt = NSDateFormatter()
//        //指定格式化方式
//        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
//        //指定本地化信息
//        dt.locale = NSLocale(localeIdentifier: "en_US")
//        let creatAtDate = dt.dateFromString(creatAtStr)!
//        //对比年份
//        if isThisYear(creatAtDate) {
//            //日历对象
//            let calender = NSCalendar.currentCalendar()
//            if calender.isDateInToday(creatAtDate) {
//                let timeinterval = abs(creatAtDate.timeIntervalSinceNow)
//                if timeinterval < 60 {
//                    return "刚刚"
//                }else if timeinterval < 60 * 60 {
//                    let result = timeinterval / 60
//                    return "\(Int(result))分钟前"
//                }else {
//                    let result = timeinterval / 3600
//                    return "\(Int(result))小时前"
//                }
//                
//            } else if calender.isDateInYesterday(creatAtDate) {
//                dt.dateFormat = "昨天 HH:mm"
//            }else {
//                dt.dateFormat = "MM-dd HH:mm"
//            }
//        }else {
//            dt.dateFormat = "yyyy-MM-dd HH:mm"
//        }
//        return dt.stringFromDate(creatAtDate)
        
    }
    // MARK:  判断微博发送的时间 跟当前的年份的对比
//    private func isThisYear(creatDate:NSDate) -> Bool {
//        let dt = NSDateFormatter()
//        dt.dateFormat = "yyyy"
//        dt.locale = NSLocale(localeIdentifier: "en_US")
//        //吧时间对象转换成字符串
//        let creatYear = dt.stringFromDate(creatDate)
//        //吧当前时间对象转换成字符串
//        let currentYear = dt.stringFromDate(NSDate())
//        
//        return creatYear == currentYear
//        
//    }
    
    //处理会员等级
    private func handleMBrankImage(mbrank:Int) {
        if mbrank >= 1 && mbrank <= 6 {
            let image = UIImage(named: "common_icon_membership_level\(mbrank)")
            mbrankImage = image
        }
    }
    //处理字符串来源
    private func handleSourceContent(source:String) {
        guard let range1 = source.rangeOfString("\">"),let range2 = source.rangeOfString("</") else {
            return
        }
        let startIndex = range1.endIndex
        let endIndex = range2.startIndex
        //截图的字符串
        sourceContent = source.substringWithRange(startIndex..<endIndex)
    }
    
    // 处理认证等级的显示
    private func handleVerifiedTypeImage(verifiedType:Int) {
        switch verifiedType {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
            
            
        }
    }
    // MARK:  处理转发微博的内容显示
    private func handleReweetContent(status:CLStatus){
        
        if status.reweeted_status != nil {
            //获取转发用户名
            guard let name = status.reweeted_status?.user?.screen_name, let text = status.reweeted_status?.text else {
                return
            }
            //此时转发的微博一定有内容
            reweetContent = "@\(name):\(text)"
            //转发微博富文本
            retweetAttributedStr = handleEmoiconContentWithAttachment(reweetContent!)
        }
    }
    // MARK:  处理原创微博内容的富文本 返回一个富文本  可以在页面直接显示
    private func handleEmoiconContentWithAttachment(content:String) ->NSAttributedString{
        
        let result = NSMutableAttributedString(string: content)
        //定义一个空的数组  用来存储遍历出来的字符
        var matchResultArray = [CLMatchResult]()
//        根据正则表达式  来遍历
        (content as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (matchCount, matchString, matchRange, _) -> Void in
            if let chs = matchString.memory as? String {
               //保存匹配结果
                let matchResult = CLMatchResult(matchString: chs, matchRange: matchRange.memory)
                //添加到数组
                matchResultArray.append(matchResult)
            }
        }
        
        for value in matchResultArray.reverse() {
  
            //查找表情模型
            if let emoicon = CLEmoiconTools.sharedTools.selectEmoiconWithChs(value.matchString) {
                 print(value.matchRange)
                //根据表情模型生成富文本属性
                let attributedStr = NSAttributedString.attribuedStringWithEmoicon(emoicon, font: UIFont.systemFontOfSize(15))
               
                //根据表情描述的位置 替换成表情模型
                result.replaceCharactersInRange(value.matchRange, withAttributedString: attributedStr)
            }
        }
        
        return result
    }
    // MARK:  toolbar显示样式
    private func handleCount(count :Int ,title :String ) ->String {
        
        if count > 0{
            if count > 10000{
                //进行格式化转换
                let result = Float(count/1000)/10
                var resultStr = "\(result)万"
                if resultStr.containsString(".0"){
                    resultStr = resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                }
                return resultStr
            }else {
                return "\(count)"
            }
        }else {
            return title
        }
        
    }
    
}
